package org.ivwsqii.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;


/************************************************
 * @ClassName: ZkClientTest.java
 * @Tables:
 * @Author:
 * @CreateDate: 2019/4/30
 * @RevisionHistory:
 ***********************************************/
public class ZkClientTest {

    private static final String CONNECTION_STRING = "192.168.1.204:2181";
    private static final int SESSION_TIME_OUT = 30000;
    private static final String IDPASSWORD = "hadoop:hadoop";
    private static final String PARENT_PATH = "parent";
    private static final String CHILD_PATH = "child";
    CountDownLatch latch = new CountDownLatch(1);
    ConfigWatcher watcher = new ConfigWatcher();
    ZooKeeper client;

    //链接
    public void connection() throws IOException, InterruptedException {
        client = new ZooKeeper(CONNECTION_STRING,SESSION_TIME_OUT, watcher);
        client.addAuthInfo("digest",IDPASSWORD.getBytes());

        latch.await();
    }

    //创建
    public void create() throws NoSuchAlgorithmException, KeeperException, InterruptedException {
        Stat exists = client.exists(PARENT_PATH, false);
        if (null != exists){
            client.delete(PARENT_PATH,-1);
        }
        client.create(PARENT_PATH,null, getAcl(), CreateMode.PERSISTENT);
        client.create(CHILD_PATH,null, getAcl(), CreateMode.PERSISTENT);
    }
    //权限
    public List<ACL> getAcl() throws NoSuchAlgorithmException {
        List<ACL> acls = new ArrayList<>();
        String scheme = "auth";
        Id id = new Id(scheme, DigestAuthenticationProvider.generateDigest(IDPASSWORD));
        ACL acl = new ACL(ZooDefs.Perms.ALL, id);
        acls.add(acl);
        return acls;
    }
    //获取
    public void getNodes() throws KeeperException, InterruptedException {
        Stat parentStat = new Stat();
        byte[] data = client.getData(PARENT_PATH, watcher, parentStat);
        List<String> children = client.getChildren(PARENT_PATH, watcher, parentStat);
    }
}
